<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="false"
    :okAuth="'rd:db:transferorder:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #transferordersList>
        <BasicTable
          @register="registerTransferordersTable"
          @row-click="handleTransferordersRowClick"
        />
        <!-- <a-button class="mt-2" @click="handleTransferordersAdd" v-auth="'rd:db:transferorder:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsWmsRdDbTransferorderForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { Transferorder, transferorderSave, transferorderForm } from '/@/api/wms/rd/db/transferorder';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('rd.db.transferorder');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<Transferorder>({} as Transferorder);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增调拨') : t('编辑调拨'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('单据编号'),
      field: 'fbillno',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('日期'),
      field: 'fdate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
    },
    {
      label: t('备注'),
      field: 'fexplanation',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('制单人'),
      field: 'fbiller',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('来源标识'),
      field: 'sourceFlag',
      component: 'Select',
      componentProps: {
        dictType: 'bas_source_type',
        allowClear: true,
        maxlength: 10,
      },
    },
    {
      label: t('公司编码'),
      field: 'companyCode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('公司名称'),
      field: 'companyName',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
    },
    {
      label: t('是否推送'),
      field: 'bsend',
      component: 'Select',
      componentProps: {
        maxlength: 10,
        dictType: 'sys_yes_no',
      },
    },
    {
      label: t('调拨单子表'),
      field: 'transferordersList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'transferordersList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerTransferordersTable, transferordersTable] = useTable({
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    showCustomSummary: true,
  });

  async function setTransferordersTableData(_res: Recordable) {
    transferordersTable.setColumns([
      {
        title: t('行号'),
        dataIndex: 'fentryid',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('物料代码'),
        dataIndex: 'basInv.viewCode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('物料名称'),
        dataIndex: 'fitemname',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('计划调拨数量'),
        dataIndex: 'fplanqty',
        width: 130,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        showSummary: true,
      },
      {
        title: t('实际调拨数量'),
        dataIndex: 'frealqty',
        width: 130,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        showSummary: true,
      },
      {
        title: t('调出仓库编码'),
        dataIndex: 'fscstockno',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('调出仓库名称'),
        dataIndex: 'fscstockname',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('调入仓库编码'),
        dataIndex: 'fdcstockno',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('调入仓库编码'),
        dataIndex: 'fdcstockname',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('备注'),
        dataIndex: 'fremarks',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 2000,
        },
        editRule: false,
      },
      {
        title: t('状态'),
        dataIndex: 'rkStatus',
        width: 100,
        align: 'left',
        editRow: false,
        dictType: 'wms_rd10_status',
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'wms_rd10_status',
        },
        editRule: false,
      },
      {
        title: t('累计上架数量'),
        dataIndex: 'sumRkQty',
        width: 130,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        showSummary: true,
      },
      {
        title: t('累计下架数量'),
        dataIndex: 'sumCkQty',
        width: 130,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
        showSummary: true,
      },
      {
        title: t('形象刊'),
        dataIndex: 'freeVO.cfree1',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
    ]);
    transferordersTable.setTableData(record.value.transferordersList || []);
  }

  function handleTransferordersRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleTransferordersAdd() {
    transferordersTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleTransferordersDelete(record: Recordable) {
    transferordersTable.deleteTableDataRecord(record);
  }

  async function getTransferordersList() {
    let transferordersListValid = true;
    let transferordersList: Recordable[] = [];
    for (const record of transferordersTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        transferordersListValid = false;
      }
      transferordersList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of transferordersTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      transferordersList.push({
        ...record,
        status: '1',
      });
    }
    if (!transferordersListValid) {
      throw { errorFields: [{ name: ['transferordersList'] }] };
    }
    return transferordersList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await transferorderForm(data);
    record.value = (res.transferorder || {}) as Transferorder;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setTransferordersTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.transferordersList = await getTransferordersList();
      // console.log('submit', params, data, record);
      const res = await transferorderSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
